<?php 

/**
 * 分类模型
 */
class CategoryModel extends Model{
	
    public $table = 'category';
    
    public $auto = array();
    
    public $validate = array(
    		array('cname', 'nonull', '分类名称不能为空'),
    		array('cname', 'maxlen:16', '分类名称不能超过16个字符'),
	);
    
	// 添加
    public function addData(){
        if (!$this->create()) return false;
		return $this->add();
    }

	// 修改
	public function editData(){
		if (!$this->create()) return false;
	    $this->update();
		return true;
	}	
	
	// 获取$cid下的所有子类的gid
	public function getGids($cid){
		// 获取$cid的所有子节点
		$cids = $this->getSonCids($cid);
		$gids = K('Goods')->where("category_cid IN (" . implode(',', $cids) . ")")->getField('gid', true);
		return $gids;
	}
	
	// 获取$cid的所有子节点
	public function getSonCids($cid){
	    $result = $this->_getSon($this->all(), $cid);
		$result[] = $cid;		
		return $result;
	}
	
	private function _getSon($cateData, $cid){
		$result = array();	
		foreach ($cateData as $v) {
	    		if ($v['pid'] == $cid){
	    			$result[] = $v['cid'];
				$result = array_merge($result, $this->_getSon($cateData, $v['cid'])); 				
	    		}
	    }
		return $result;
	}
 }
 
 
 
 
 
 
 
 
 
 
 


 ?>